package cn.com.dcsgo.service.impl;

import cn.com.dcsgo.exception.UuPreferredException;
import cn.com.dcsgo.model.sys.RegionWare;
import cn.com.dcsgo.mapper.RegionWareMapper;
import cn.com.dcsgo.result.ResultCodeEnum;
import cn.com.dcsgo.service.RegionWareService;
import cn.com.dcsgo.vo.sys.RegionWareQueryVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

/**
 * <p>
 * 城市仓库关联表 服务实现类
 * </p>
 *
 * @author Dcsgo
 * @since 2025-04-01
 */
@Service
public class RegionWareServiceImpl extends ServiceImpl<RegionWareMapper, RegionWare> implements RegionWareService {

    @Override
    public IPage<RegionWare> selectRegionWarePage(Page<RegionWare> pageParam, RegionWareQueryVo regionWare) {
        //构造查询条件
        String keyword = regionWare.getKeyword();
        LambdaQueryWrapper<RegionWare> wrapper = new LambdaQueryWrapper<>();
        if (!StringUtils.isEmpty(keyword)) {
            //根据区域名称或仓库名称模糊查询
            wrapper.like(RegionWare::getRegionName, keyword)
                    .or().like(RegionWare::getWareName, keyword);
        }
        //进行分页查询
        return baseMapper.selectPage(pageParam, wrapper);
    }

    @Override
    public void saveRegionWare(RegionWare regionWare) {
        //判断区域是否已开通->region_ware中是否存在该记录
        LambdaQueryWrapper<RegionWare> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(RegionWare::getRegionId, regionWare.getRegionId())
                .eq(RegionWare::getWareId, regionWare.getWareId());
        //存在->抛出自定义异常-交给全局异常处理器处理
        if (baseMapper.selectCount(wrapper) > 0) {
            throw new UuPreferredException(ResultCodeEnum.REGION_OPEN);
        }
        //没开通->正常添加
        baseMapper.insert(regionWare);
    }
}
